import Vue from 'vue'
import Vuex from 'vuex'
const axios = require('axios')
Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    classinfo: [], // page1的获取课程信息的变量
    objtobackend: {}, //page2 post方法中的待提交数据
    objfrombackend: [], //page2 get all方法中的所有数据
    objfilter: [], //数据上与objfrombackend一样 视作备份 用于筛选数据
    objget: {} //单条数据返回
  },
  getters: {
  },
  mutations: {
    updateclassInfo(state, newdata) {
      newdata.forEach(function (value, index, array) {
        value["pic_address"] = require("@/assets/" + value['pic_address']);
      })
      state.classinfo = newdata
    },
    getallobj(state, newdata) {
      state.objfrombackend = newdata
      state.objfilter = newdata
    },
    getoneobj(state, newdata) {
      state.objget = newdata
      console.log(state.objget)
    },
    updateobj(state, newdata) {
      state.objtobackend = newdata
    },
    search(state, str) {
      const datafilter = state.objfilter.filter((data) => {
        return data['name'].indexOf(str) != -1
      })
      state.objfrombackend = datafilter
    },
  },
  actions: {
    getfrontdata(context) {
      axios.get("http://localhost:8080/frontapi/classfrontinfo/").then(resp => {
        if (resp.data.length <= 5) {
          context.commit("updateclassInfo", resp.data)
        }
        else {
          context.commit("updateclassInfo", resp.data.slice(0, 5))
        }
      }, error => {
        alert("数据获取失败")
      })
    },
    postobj(context, newobj) {
      context.commit("updateobj", newobj[0])
      axios.post("http://localhost:8080/backapi/classinfo/", context.state.objtobackend).then(resp => {
        console.log(resp.data)
        newobj[1](resp.data.id)
        alert("提交成功")
      }, error => {
        alert("数据上传失败,请检查网络")
      })
    },
    getallobj(context) {
      axios.get("http://localhost:8080/backapi/classinfo/").then(resp => {
        context.commit("getallobj", resp.data)
      }, error => {
        alert("数据获取失败,请检查网络")
      })
    },
    getoneobject(context, id) {
      axios.get("http://localhost:8080/backapi/classinfo/" + id).then(resp => {
        context.commit("getoneobj", resp.data)
        return resp.data
      }, error => {
        alert("数据获取失败,请检查网络")
      })
    },
    updateobj(context, newobj) {
      axios.put("http://localhost:8080/backapi/classinfo/" + newobj[1] + "/", newobj[0]).then(resp => {
        alert("更新成功")
      }, error => {
        alert("数据上传失败,请检查网络")
      })
    },
    partialupdateobj(context, newobj) {
      axios.patch("http://localhost:8080/backapi/classinfo/" + newobj[1] + "/", newobj[0]).then(resp => {
        alert("更新成功")
      }, error => {
        alert("数据上传失败,请检查网络")
      })
    },
    deleteobj(context, id) {
      axios.delete("http://localhost:8080/backapi/classinfo/" + id).then(resp => {
        alert("删除成功")
      }, error => {
        alert("数据上传失败,请检查网络")
      })
    }
  },
  modules: {
  }
})
